﻿var SpecialDatesValidationClientSideHide = false;
var PageNumber = 1;
var IsSearchView = false;
var SpecialDatesIDView = 0;
var IsDeleteView = false;
var ChangeElementID = 0;
var SpecialDatesComElem = null;
var SpecialDatesComElemVal = null;
var SpecialDatesTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("SetupSpecialDates") != -1) {
        $.validator.addMethod("SetupSpecialDatesRequireds", $.validator.methods.required, Messages["SetupSpecialDatesRequireds"]);
        $.validator.addMethod("SetupSpecialDatesMaxLength50", $.validator.methods.maxlength, Messages["SetupSpecialDatesMaxLength50"]);
        $.validator.addMethod("SetupSpecialDatesMaxLength20", $.validator.methods.maxlength, Messages["SetupSpecialDatesMaxLength20"]);
        $.validator.addMethod("SetupSpecialDatesDate", $.validator.methods.datePicker, Messages["SetupSpecialDatesDate"]);
        $.validator.addClassRules({
            Required: {
                SetupSpecialDatesRequireds: true,
            },
            MaxLength50: {
                SetupSpecialDatesMaxLength50: 50,
            },
            MaxLength20: {
                SetupSpecialDatesMaxLength20: 20,
            },
            Date: {
                SetupSpecialDatesDate: true,
            },
        });

        $('#LoadSpecialDatesDetailsForm').validate();
        LoadSpecialDatesGrid();
        InitSpecialDatesDetailsDataCalendarsFromToSeacrh();
    }
});
$(document).on('change', '.ChangedSpecialDatesElements', function () {
    $('#SpecialDatesDetailsSaveBtn').addClass('BackColorRed');
});
$(document).on('change', '.SpecialDatesAddElementChange', function () {
    $('#SpecialDateAddBtn').addClass('BackColorRed');
});
function DeleteSpecialDate(SpecialDatesID) {
    jConfirm('Are you sure you want to delete this Detail?', 'Warning!', function (retVal) {
        if (retVal == true) {
            SpecialDatesIDView = SpecialDatesID;
            IsDeleteView = true;
            LoadSpecialDatesGrid();
        }
    });
}
function InitSpecialDatesDetailsDataCalendarsGridFromTo() {
    $(".SpecialDatesDeteilsDataCalendarGridFrom").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 99,
            });
        },
        onClose: function (selectedDate) {
            $(this).parent().parent().find(".SpecialDatesDeteilsDataCalendarGridTo").datepicker("option", "minDate", selectedDate);
        }
    });
    $(".SpecialDatesDeteilsDataCalendarGridTo").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 99,
            });
        },
        onClose: function (selectedDate) {
            $(this).parent().parent().find(".SpecialDatesDeteilsDataCalendarGridFrom").datepicker("option", "maxDate", selectedDate);
        }
    });
}

function InitSpecialDatesDetailsDataCalendarsFromToDiv() {
    $("#AddSpecialDatesStartDate").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 9999999,
            });
        },
        onClose: function (selectedDate) {
            $("#AddSpecialDatesEndDate").datepicker("option", "minDate", selectedDate);
        }
    });
    $("#AddSpecialDatesEndDate").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 9999999,
            });
        },
        onClose: function (selectedDate) {
            $("#AddSpecialDatesStartDate").datepicker("option", "maxDate", selectedDate);
        }
    });
}
function InitSpecialDatesDetailsDataCalendarsFromToSeacrh() {
    $("#SpecialDatesStartDateText").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 99,
            });
        },
        onClose: function (selectedDate) {
            $("#SpecialDatesEndDateText").datepicker("option", "minDate", selectedDate);
        }
    });
    $("#SpecialDatesEndDateText").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 99,
            });
        },
        onClose: function (selectedDate) {
            $("#SpecialDatesStartDateText").datepicker("option", "maxDate", selectedDate);
        }
    });
}
function AddNewSpecialDate() {
    SpecialDatesValidationClientSideHide = false;
    $.ajax({
        url: urls["SetupAddNewSpecialDate"],
        type: 'GET',
        success: function (data) {
            $("#AddNewSpecialDateDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            IsDeleteView = false;
            AddNewSpecialDatePopUp("AddNewSpecialDateDiv");
            InitSpecialDatesDetailsDataCalendarsFromToDiv()
        }
    });
}
$(document).on('click', '#SpecialDatesMoreBtn', function () {
    PageNumber = PageNumber + 1;
    IsDeleteView = false;
    LoadSpecialDatesGrid();
});
$(document).on('click', '#SpecialDatesSearchBtn', function () {
    IsSearchView = true;
    IsDeleteView = false;
    LoadSpecialDatesGrid();
});
function AddNewSpecialDatePopUp(PopUpDiv) {
    $.colorbox({
        width: "700px",
        height: "360px",
        inline: true,
        href: "#" + PopUpDiv,
        onComplete: function () {
            $("#" + PopUpDiv).show();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
$(document).on('click', '#SpecialDateAddBtn', function () {
    var $form = $('#AddNewSpecialDateForm');
    if ($form.valid()) {
        SpecialDatesValidationClientSideHide = false;
        if (AddTimeAreCheckedAnyVendorType()) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error");
                },
                complete: function () {
                    $('#SpecialDateAddBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    $('#cboxClose').click();
                    IsDeleteView = false;
                    LoadSpecialDatesGrid();
                }
            });
        }
        else
            jAlert("If no vendor we must choose any vendor type:", "Attention!");
    }
    else
        SpecialDatesValidationClientSideHide = true;
});
$(document).on('click', '#SpecialDatesDetailsSaveBtn', function () {
        var $form = $('#LoadSpecialDatesDetailsForm');
        if ($form.valid()) {
            if ($form[0].length > 0) {
                if (AreCheckedAnyVendorType()) {
                    $.ajax({
                        url: $form.attr('action'),
                        type: $form.attr('method'),
                        data: $form.serialize(),
                        beforeSend: function (xhr) {
                            xhr.overrideMimeType('text/plain; charset=x-user-defined');
                        },
                        success: function (data) {
                            if (data.indexOf("Error") != -1)
                                jAlert(data, "Error");
                        },
                        error: function (xhr) {
                            jAlert(xhr.statusText, "Error");
                        },
                        complete: function () {
                            $('#SpecialDatesDetailsSaveBtn').removeClass('BackColorRed')
                            jAlert("Data SuccessFully Saved:", "Successful");
                            IsDeleteView = false;
                            LoadSpecialDatesGrid();
                        }
                    });
                }
                else
                    jAlert("If no vendor we must choose any vendor type:", "Attention!");
            }
            else
                jAlert("You have not data to save:", "Attention!");
        }
});
function LoadSpecialDatesGrid() {
    var SetupSpecialDatesGridViewModel = {
        SelectedSpecialDatesCityIDText: $("#SelectedSpecialDatesCityIDText").val(),
        SpecialDatesStartDateText: $("#SpecialDatesStartDateText").val(),
        SpecialDatesEndDateText: $("#SpecialDatesEndDateText").val(),
        PageNum: parseInt(PageNumber),
        IsSearch: IsSearchView,
        IsDelete: IsDeleteView,
        SpecialDatesID: parseInt(SpecialDatesIDView),
        IsActiveSearch: $("#IsActiveSearch").val(),
    };

    var DTO = JSON.stringify(SetupSpecialDatesGridViewModel);
    $.ajax({
        url: urls["SetupLoadSpecialDatesGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#SetupSpecialDatesGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            SpecialDatesElementsDrop();
            InitSpecialDatesDetailsDataCalendarsGridFromTo();
        }
    });
}
function SpecialDatesElementsDrop()
{
    $(".SpecialDatesElementsDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.SpecialDatesElementsDrop', function () {
    $(".SpecialDatesElementsDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
$(document).on('change', '.CountryDrop', function () {
    $(".CountryDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
        var element = $(this).parent();
        var tdparent = element.parent();
    });
    var element = $(this).parent();
    var tdparent = element.parent();
    $.ajax({
        url: urls["SetupGetCity"],
        data: { CountryID: parseInt($(this).val()) },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Select</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }
            $(tdparent).find("Select.ForChangeCityFromCountry").html(markup).show();
            $(tdparent).find("Select.ForChangeCityFromCountryImit").html(markup);
        },
        error: function (reponse) {
            jAlert(reponse, "Error");
        },
        complete: function () {
            SpecialDatesElementsDrop();
        }
    });
});
$(document).on('change', '.AddCityDrop', function () {
    $(".AddCityDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
$(document).on('change', '.AddCountryDrop', function () {
    $(".AddCountryDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
    var element = $(this).parent();
    var tdparent = element.parent();
    $.ajax({
        url: urls["SetupGetCity"],
        data: { CountryID: parseInt($(this).val()) },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Select</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }
            $("Select.AddForChangeCityFromCountry").html(markup).show();
            $("Select.AddForChangeCityFromCountryImit").html(markup);
        },
        error: function (reponse) {
            jAlert(reponse, "Error");
        },
        complete: function () {
        }
    });
});
// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (SpecialDatesTimerId == null) {
        SpecialDatesComElem = $(this).attr('id');
        SpecialDatesComElemVal = $("#" + SpecialDatesComElem).val();
        SpecialDatesTimerId = setInterval(function () {

            var keyword = $("#" + SpecialDatesComElem).val();
            if (keyword == SpecialDatesComElemVal) {
                var PropName = "";
                if (SpecialDatesComElem.indexOf("VendorName") != -1) {
                    PropName = "VendorName";
                    $("#" + SpecialDatesComElem).next().val(null);
                    if($("#" + SpecialDatesComElem).hasClass('VendorFromGrid'))
                    {
                        var Tr = []
                        Tr = $("#" + SpecialDatesComElem).parent().parent().find('.MakeReadOnlyInsetVendorTime');
                        $(Tr).each(function (index, elem) {
                            $(elem).removeAttr('Disabled')
                        });
                        City = $("#" + SpecialDatesComElem).parent().parent().find('.IsRemoveCityRequired');
                        if (!$(City).hasClass('Required'))
                            $(City).addClass('Required')
                    }
                    else
                    {
                        $("#SpecialDatesIsHotel").removeAttr('Disabled');
                        $("#SpecialDatesIsAttraction").removeAttr('Disabled');
                        $("#SpecialDatesIsRestaurant").removeAttr('Disabled');
                        $("#SpecialDatesIsMisc").removeAttr('Disabled');
                        $("#SpecialDatesIsBus").removeAttr('Disabled');
                        if (!$("#AddSelectedSpecialDatesCityID").hasClass('Required'))
                            $("#AddSelectedSpecialDatesCityID").addClass('Required');
                    }
                }

                var position = $("#" + SpecialDatesComElem).offset();
                position.top = position.top + $("#" + SpecialDatesComElem).height() + 5;
                $.ajax({
                    url: urls["SetupAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + SpecialDatesComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(SpecialDatesTimerId);
                        SpecialDatesTimerId = null;
                    }
                });
            }
            else
                SpecialDatesComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + SpecialDatesComElem).val(val);
    if (SpecialDatesComElem.indexOf("VendorName") != -1) {
        $("#" + SpecialDatesComElem).next().val(key);
        if ($("#" + SpecialDatesComElem).hasClass('VendorFromGrid')) {
            var Tr = []
            Tr = $("#" + SpecialDatesComElem).parent().parent().find('.MakeReadOnlyInsetVendorTime');
            $(Tr).each(function (index, elem) {
                $(elem).prop('checked', false);
                $(elem).attr('disabled', true);
            });
            City = $("#" + SpecialDatesComElem).parent().parent().find('.IsRemoveCityRequired');
            if ($(City).hasClass('Required'))
                $(City).removeClass('Required')
        }
        else {
            $("#SpecialDatesIsHotel").prop('checked', false);
            $("#SpecialDatesIsHotel").attr('disabled', true);
            $("#SpecialDatesIsAttraction").prop('checked', false);
            $("#SpecialDatesIsAttraction").attr('disabled', true);
            $("#SpecialDatesIsRestaurant").prop('checked', false);
            $("#SpecialDatesIsRestaurant").attr('disabled', true);
            $("#SpecialDatesIsMisc").prop('checked', false);
            $("#SpecialDatesIsMisc").attr('disabled', true);
            $("#SpecialDatesIsBus").prop('checked', false);
            $("#SpecialDatesIsBus").attr('disabled', true);
            if ($("#AddSelectedSpecialDatesCityID").hasClass('Required'))
                $("#AddSelectedSpecialDatesCityID").removeClass('Required');
        }
    }
    $("#AutoCompleteDiv").hide();
}


var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#SpecialDateAddBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddNewSpecialDateForm").empty();
                LoadSpecialDatesGrid();
                originalClose();
            }
        });
    }
    else {
        $("#AddNewSpecialDateForm").empty();
        LoadSpecialDatesGrid();
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (SpecialDatesValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});
$(document).on('change', '.ForValidation', function () {
    if ($(this).valid)
        $(this).removeClass('table_inputs_Unvalidated');
    if ($(this).closest("form").valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            if ($(this).valid())
                $(this).removeClass('table_inputs_Unvalidated');
        });
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
});
function AddTimeAreCheckedAnyVendorType()
{
    var Valid = false;
    if(parseInt($("#AddVendorID").val()) > 0)
    {
        Valid = true;
    }
    else
    {
        $(".AddCheckboxForValidate").each(function (index, elem) {
            if ($(elem).is(":checked")) {
                Valid = true;
                return;
            }
        });
    }
    return Valid;
}
function AreCheckedAnyVendorType() {
    var Valid = true;
    $(".VendorID").each(function (index, elem) {
        if (!(parseInt($(elem).val()) > 0)) {
            var CheckedChechbox = $(elem).parent().parent().find('.MakeReadOnlyInsetVendorTime:checkbox:checked');
            if (!(CheckedChechbox.length > 0)) {
                Valid = false;
                return;
            }
        }
    });
    return Valid;
}